package com.example.serialtool

import android.serialport.SerialPort
import java.io.File
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream

class SerialPortManager {

    private var serialPort: SerialPort? = null
    private var inputStream: InputStream? = null
    private var outputStream: OutputStream? = null

    fun open(port: String, baudRate: Int): Boolean {
        return try {
            serialPort = SerialPort(File(port), baudRate)
            inputStream = serialPort?.inputStream
            outputStream = serialPort?.outputStream
            true
        } catch (e: IOException) {
            e.printStackTrace()
            false
        }
    }

    fun close() {
        // 实现关闭串口的逻辑
        try {
            inputStream?.close()
            outputStream?.close()
            serialPort?.close()
        } catch (e: IOException) {
            e.printStackTrace()
        } finally {
            inputStream = null
            outputStream = null
            serialPort = null
        }
    }

    fun write(data: ByteArray) {
        try {
            outputStream?.write(data)
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    fun read(buffer: ByteArray): Int {
        return try {
            inputStream?.read(buffer) ?: -1
        } catch (e: IOException) {
            e.printStackTrace()
            -1
        }
    }
}
